package com.mapler.ui;

import com.mapler.utility.HttpHelper;
import com.mapler.utility.IConstant;
import java.awt.Color;
import java.net.URL;
import java.util.List;
import javax.swing.table.DefaultTableModel;
import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Node;

/**
 *
 * @author none
 */
public class AdViewUI extends javax.swing.JPanel {

    private javax.swing.JButton jButtonDelete;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTableAd;
    private javax.swing.JLabel message;
    private javax.swing.JTextField recordIdUI;
    private javax.swing.JTextField titleUI;
    
    private String[] COLUMNS = {"ID", "Title", "Description","Remarks"};
    private DefaultTableModel model = new DefaultTableModel(COLUMNS, 0);
    
    private String username;
    private String password;
    private String country;
    
    private static Logger log = Logger.getLogger(AdViewUI.class);
    public AdViewUI() {
        initComponents();
    }
    
     public AdViewUI(String username, String password,String country) {
         this.username = username;
         this.password = password;
         this.country = country;
         initComponents();
    }
     
    private void initComponents() {

        message = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        recordIdUI = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        titleUI = new javax.swing.JTextField();
        jButtonDelete = new javax.swing.JButton();
        jButtonDelete.addActionListener(new java.awt.event.ActionListener() {
            @Override
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                actionDeleteHandler(evt);
            }
        });
        jScrollPane1 = new javax.swing.JScrollPane();
        jTableAd = new javax.swing.JTable(model);
        jTableAd.addMouseListener(new java.awt.event.MouseAdapter() {
            @Override
            public void mouseClicked(java.awt.event.MouseEvent e) {
                int row = jTableAd.rowAtPoint(e.getPoint());
                int col = jTableAd.columnAtPoint(e.getPoint());
                recordIdUI.setText(jTableAd.getValueAt(row, 0).toString());
                titleUI.setText(jTableAd.getValueAt(row, 1).toString());
                //System.out.println(row + ":" + col + ": Value in the cell clicked:" + jTableAccount.getValueAt(row, col).toString());
            }
        });
        jLabel2.setText("ID");
        jLabel3.setText("Title");
        jButtonDelete.setText("Delete");
        
        jScrollPane1.setViewportView(jTableAd);
        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                .addContainerGap(21, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                .addComponent(message, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jButtonDelete)
                .addGroup(layout.createSequentialGroup()
                .addComponent(jLabel2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(recordIdUI, javax.swing.GroupLayout.PREFERRED_SIZE, 84, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(jLabel3)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(titleUI, javax.swing.GroupLayout.PREFERRED_SIZE, 384, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addGap(61, 61, 61))
                .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 617, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap()))));
        layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(message, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(jLabel2)
                .addComponent(recordIdUI, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(jLabel3)
                .addComponent(titleUI, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButtonDelete)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 17, Short.MAX_VALUE)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 331, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(26, 26, 26)));
    }
    
    private void actionDeleteHandler(java.awt.event.ActionEvent evt) {
        try {
            StringBuilder request = new StringBuilder();
            request.append("<Request>");
            request.append("<id>").append(this.recordIdUI.getText()).append("</id>");
            request.append("<username>").append(this.username).append("</username>");
            request.append("<password>").append(this.password).append("</password>");            
            request.append("</Request>");

            String uri = "http://" + IConstant.HOSTNAME + "/index.php?r=advertisement/deleteAdvertisement&request=" + request.toString();
            
            String response = HttpHelper.post(new URL(uri), "");

            Document document = DocumentHelper.parseText(response);
            String errorCode = document.valueOf("Response/errorcode");
            String msg = document.valueOf("Response/message");
            if (errorCode.equalsIgnoreCase("000")) {
                this.message.setBackground(Color.red);
            } else {
                this.getAdvertisement();
                this.message.setBackground(Color.black);
            }
            this.message.setText(msg);
        } catch (Exception ex) {
            this.message.setText("Error "+ex.getMessage());
            log.debug("Error "+ex);
        }
    }
    
    private void clearModel() {
        for (int i = model.getRowCount() - 1; i >= 0; i--) {
            model.removeRow(i);
        }
        jTableAd.repaint();            
    }
    public void getAdvertisement() {
        try {
            this.clearModel();
            String uri = "http://" + IConstant.HOSTNAME + "/index.php?r=advertisement/getAdvertisement&username="
                    + this.username + "&password=" + this.password;
            String response = HttpHelper.post(new URL(uri), "");
            Document document = DocumentHelper.parseText(response);
            String errorCode = document.valueOf("Response/errorcode");
            if (!errorCode.equalsIgnoreCase("000")) {
                List<Node> list = document.selectNodes("/Response/accounts/account");
                for (Node node : list) {
                    Object[] row = new Object[4];
                    row[0] = node.valueOf("id");
                    row[1] = node.valueOf("title");
                    row[2] = node.valueOf("description");
                    row[3] = node.valueOf("remarks");
                    model.addRow(row);
                }
            } else {
                String message = document.valueOf("Response/message");
                this.message.setText(message);
            }
        } catch (Throwable ex) {
            this.message.setText("Error "+ex.getMessage());
            log.debug("Error "+ex);
        }
    }
}
